package com.smsVerification.service.test;

import com.smsVerification.config.HttpCode;
import com.smsVerification.pojo.CommonResult;
import com.smsVerification.service.captcha.ICaptchaInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@RefreshScope
public class CaptchaInfoServiceTestImpl {

    /**
     * 保存手机号与极光验证码ID对应关系的KEY的前缀
     */
    final String CAPTCHA_RECORD_KEY_PREFIX = "CAPTCHA:";

    /**
     * 保存手机号与极光验证码ID对应关系的MAP的KEY
     */
    final String CAPTCHA_RECORD_KEY_SUFFIX = ":VALUE";

    /**
     * 保存手机号发送了多少次验证码的MAP的KEY
     */
    final String CAPTCHA_COUNT_MAP_KEY = "CAPTCHA:COUNT:MAP";

    /**
     * 消息是否正确的JSON KEY
     */
    final String MESSAGE_IS_VALID_KEY = "is_valid";

    /**
     * 验证码每日请求的最大数量
     */
    @Value("${captcha.max-request-per-day}")
    int CAPTCHA_MAX_REQUEST_PER_DAY;

    /**
     * 极光开发APP KEY
     */
    @Value("${jiguang.jpush.app-key}")
    String JPUSH_APP_KEY;

    /**
     * 极光开发MASTER SECRET
     */
    @Value("${jiguang.jpush.master-secret}")
    String JPUSH_MASTER_SECRET;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取对应手机号在Redis中的key
     * 举例：CAPTCHA:13577401518:VALUE
     *
     * @return 手机号在Redis中的key
     */
    String getRecordKey(String phone) {
        return CAPTCHA_RECORD_KEY_PREFIX + phone + CAPTCHA_RECORD_KEY_SUFFIX;
    }

    /**
     * 判断验证码和手机号是否匹配
     * 参考文档： https://docs.jiguang.cn/jsms/server/rest_api_jsms#请求示例-2
     *
     * @param captcha     验证码
     * @param phoneNumber 手机号
     * @return 是否正确
     */
    public CommonResult<Boolean> checkCaptcha(int captcha, String phoneNumber) {
        //获取Key
        String recordKey = getRecordKey(phoneNumber);
        //查询手机号对应的验证码ID
        Object queryResult = redisTemplate.opsForValue().get(recordKey);
        //如果为空，说明没有记录，直接返回
        if (queryResult == null) {
            return new CommonResult<>(HttpCode.WRONG_PARAM, "无发送记录", null);
        }

        //调用 验证码验证api
        // ...

        return new CommonResult<>(HttpCode.SUCCESS, "成功", true);

    }

    public Boolean isCaptchaRequestAvailable(String phoneNumber) {
        //获得每日发送的次数的Redis Key
        Object countQueryObject = redisTemplate.opsForHash().get(CAPTCHA_COUNT_MAP_KEY, phoneNumber);

        //如果是NULL，说明数据库里还没有这个数据，就允许发送
        if (countQueryObject == null) {
            return true;
        } else {
            //查询当前已经发送的次数
            int count = Integer.parseInt(String.valueOf(countQueryObject));
            //判断是否查出了最大次数
            return count <= CAPTCHA_MAX_REQUEST_PER_DAY;
        }
    }


}
